#include <my_header.h>
// B从write.pipe中读取数据 从read.pipe中写入数据
// 从read.pipe中输入数据时 需要从stdin读取 在写入
/* Usage: ./4_UserB_duplex */
int main(int argc, char *argv[]){              
    // 从write.pipe读UserA输入的内容
    int fd_read = open("write.pipe", O_RDONLY);
    // 写入数据到read.pipe UserA待读取
    int fd_write = open("read.pipe", O_WRONLY);
    ERROR_CHECK(fd_read, -1, "open read");
    ERROR_CHECK(fd_write, -1, "open write");

    while(1)
    {
        char buf[60] = {0};
        bzero(buf, sizeof(buf));
        // 读取write.pipe:打印到标准输出
        int read_num =read(fd_read, buf, sizeof(buf));
        if(read_num == 0 )
        {
            printf("对方断开连接 \n");
            break;
        }
        printf("UserA: %s", buf);
        // 清空buf缓冲区 为了写入数据
        bzero(buf, sizeof(buf));
        // 读取标准输入：通过read.pipe发送给UserA
        int read_stdin = read(STDIN_FILENO, buf, sizeof(buf));
        if(read_stdin == 0)
        {
            // 用户按下ctrl+d;输入文件终止符；
            // 终止标准输入；read返回0
            break;
        }
        // 写入管道read.pipe
        write(fd_write, buf, sizeof(buf));
    }
    // 关闭文件描述符
    close(fd_write);
    close(fd_read);
    return 0;
}


